package com.itbaizhan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itbaizhan.domain.Orders;
import com.itbaizhan.domain.TxLog;
import com.itbaizhan.mapper.TxLogMapper;
import com.itbaizhan.service.OrderService;
import com.itbaizhan.mapper.OrderMapper;
import com.itbaizhan.tx.TxMessage;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
* @author 13487
* @description 针对表【order】的数据库操作Service实现
* @createDate 2024-04-22 19:11:33
*/
@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private TxLogMapper txLogMapper;
//    @Resource
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void save(Long productId, Integer payCount) {
        Orders order = new Orders();
        // 订单创建时间
        order.setCreateTime(new Date());
        // 生产订单编号
        order.setOrderNo(UUID.randomUUID().toString().replace("-",""));
        // 商品id
        order.setProductId(productId);
        // 购买数量
        order.setPayCount(payCount);
        orderMapper.insert(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitOrderOrSaveTx(TxMessage txMessage) {
        TxLog txLog = txLogMapper.selectById(txMessage.getTxNo());
        if (txLog != null){
            return;
        }

        this.save(txMessage.getProductId(), txMessage.getPayCount());

        TxLog txLog1 = new TxLog();
        txLog1.setTxNo(txMessage.getTxNo());
        txLog1.setCreateTime(new Date());
        txLogMapper.insert(txLog1);
    }

    @Override
    public void submitOrder(Long productId, Integer payCount) {
        String txNo = UUID.randomUUID().toString().replace("-","");
        TxMessage txMessage = new TxMessage(productId, payCount, txNo);

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("txMessage",txMessage);
//
//        Message<String> message = MessageBuilder.withPayload(jsonObject.toJSONString()).build();
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(txMessage)).build();
        rocketMQTemplate.sendMessageInTransaction("tx_msgtopic", message, null);
    }


}




